package com.controller;

import com.annotations.RequestMappping;
import com.google.gson.Gson;
import com.pojo.TbGoodsType;
import com.service.GoodsTypeService;
import com.service.impl.GoodsTypeServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@RequestMappping("/goodtypes")

public class GoodsTypeServlet {

    private Gson gson = new Gson();

    private GoodsTypeService goodsTypeService = new GoodsTypeServiceImpl();

    @RequestMappping("/add")
    public String add(HttpServletRequest request, HttpServletResponse response) {
        try {
            goodsTypeService.addType(request.getParameter("name"), request.getParameter("Parent"));
            //更新 context 中的缓存数据
            List<TbGoodsType> goodsTypeList = (List<TbGoodsType>) request.getServletContext().getAttribute("goodsTypeList");
            List<TbGoodsType> allTypes = goodsTypeService.findAllSecondLevelType();
            goodsTypeList.clear();//清除原先的数据,一定要先清除,因为 list 允许重复
            goodsTypeList.addAll(allTypes);//重新添加
            return "redirect:/admin/showGoodsType.jsp";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/error/error.jsp";

    }

    @RequestMappping("/delete")
    public String delete(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");//要删除的 id
        int i = goodsTypeService.deleteType(id);
        if (i == -1) {
            response.setContentType("text/html;charset=utf-8");
            //不允许删除
            return "不允许删除非空节点";
        }

        try {
            //清空缓存, 重新查询
            List<TbGoodsType> goodsTypeList = (List<TbGoodsType>) request.getServletContext().getAttribute("goodsTypeList");
            List<TbGoodsType> allTypes = goodsTypeService.findAllSecondLevelType();
            goodsTypeList.clear();//清除原先的数据,一定要先清除,因为 list 允许重复
            goodsTypeList.addAll(allTypes);//重新添加
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/admin/showGoodsType.jsp";

    }

    @RequestMappping("/findAll")
    public String findAll(HttpServletRequest request, HttpServletResponse response) {

        List<TbGoodsType> allTypes = (List<TbGoodsType>) request.getServletContext().getAttribute("goodsTypeList");
        if (allTypes == null || allTypes.size() == 0) {
            try {
                allTypes = goodsTypeService.findAllSecondLevelType();
                request.getServletContext().setAttribute("goodsTypeList", allTypes);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String json = gson.toJson(allTypes);
        System.err.println(json);
        response.setContentType("application/json;charset=utf-8");
        return json;
    }
}